from flask import Blueprint, render_template, request, jsonify
from flask_login import login_required

from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import SysConfig
from applications.schemas import RoleOutSchema, PowerOutSchema2

bp = Blueprint('config', __name__, url_prefix='/config')

# 用户管理
@bp.get('/')
@authorize("system:config:main")
def main():
    return render_template('system/config/main.html')


# 表格数据
@bp.get('/data')
@authorize("system:config:main")
def table():
    role_name = str_escape(request.args.get('name', type=str))
    role_code = str_escape(request.args.get('code', type=str))
    filters = []
    if role_name:
        filters.append(SysConfig.name.contains(role_name))
    if role_code:
        filters.append(SysConfig.code.contains(role_code))
    query = SysConfig.query.filter(*filters).layui_paginate()
    return table_api(
        data=[{
            'id': config.id,
            'name': config.name,
            'code': config.code,
            'enable': config.enable,
            'details': config.details,
            'sort': config.sort,

        } for config in query.items],
        count=query.total)


# 角色增加
@bp.get('/add')
@authorize("system:config:add", log=True)
def add():
    return render_template('system/config/add.html')


# 角色增加
@bp.post('/save')
@authorize("system:config:add", log=True)
def save():
    req = request.get_json(force=True)
    details = str_escape(req.get("details"))
    enable = str_escape(req.get("enable"))
    roleCode = str_escape(req.get("code"))
    roleName = str_escape(req.get("name"))
    sort = str_escape(req.get("sort"))
    role = SysConfig(
        details=details,
        enable=enable,
        code=roleCode,
        name=roleName,
        sort=sort
    )
    db.session.add(role)
    db.session.commit()
    return success_api(msg="成功")





# 角色编辑
@bp.get('/edit/<int:id>')
@authorize("system:config:edit", log=True)
def edit(id):
    r = get_one_by_id(model=SysConfig, id=id)
    return render_template('system/config/edit.html', info=r)


# 更新角色
@bp.put('/update')
@authorize("system:config:edit", log=True)
def update():
    req_json = request.get_json(force=True)
    id = req_json.get("id")
    data = {
        "code": str_escape(req_json.get("code")),
        "name": str_escape(req_json.get("name")),
        "sort": str_escape(req_json.get("sort")),
        "enable": str_escape(req_json.get("enable")),
        "details": str_escape(req_json.get("details"))
    }
    role = SysConfig.query.filter_by(id=id).update(data)
    db.session.commit()
    if not role:
        return fail_api(msg="更新系统配置失败")
    return success_api(msg="更新系统配置成功")


# 启用用户
@bp.put('/enable')
@authorize("system:config:edit", log=True)
def enable():
    id = request.get_json(force=True).get('id')
    if id:
        res = enable_status(SysConfig, id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用用户
@bp.put('/disable')
@authorize("system:config:edit", log=True)
def dis_enable():
    _id = request.get_json(force=True).get('id')
    if _id:
        res = disable_status(SysConfig, _id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")


# 角色删除
@bp.delete('/remove/<int:id>')
@authorize("system:config:remove", log=True)
def remove(id):


    r = SysConfig.query.filter_by(id=id).delete()
    db.session.commit()
    if not r:
        return fail_api(msg="配置删除失败")
    return success_api(msg="配置删除成功")
